package com.ly.websocket.web;

import com.google.gson.Gson;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
@ServerEndpoint("/ws/{id}")
@RequestMapping("ws")
public class WebSocketDo {

    private static Map<String, Session> sessionMap = new ConcurrentHashMap<>();

    // 连接建立成功调用的方法
    @OnOpen
    public void onOpen(@PathParam("id") String id, Session session) {
        session.getUserProperties().put("id", id);
        sessionMap.put(id, session);
        System.out.println("用户上线了: " + id);
    }

    // 连接关闭调用的方法
    @OnClose
    public void onClose(Session session) {
        String id = (String) session.getUserProperties().get("id");
        sessionMap.remove(id);
        System.out.println("用户已下线: " + id);
    }

    // 收到客户端消息后调用的方法
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        final Object id = session.getUserProperties().get("id");
        System.out.println(this);
        System.out.println(id + " : " + message);
    }

    @GetMapping("onlines")
    public Object onlines(String id, String msg) throws IOException {
        return sessionMap.keySet();
    }

    @RequestMapping("send")
    public String send(String id, String msg) throws IOException {
        return send(id, (Object)msg);
    }

    public String send(String id, Object msg) throws IOException {
        final Session session = sessionMap.get(id);
        if (session != null) {
            final String json = new Gson().toJson(msg);
            session.getBasicRemote().sendText(json);
            return "消息成功发送给: " + id;
        } else {
            return "用户未登录: " + id;
        }
    }

    @RequestMapping("")
    public ModelAndView index(ModelAndView mav){
        mav.setViewName("redirect:/ws/index.html");
        return mav;
    }

}
